import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from bookshop import models
from bookshop.sers import BookModelSerializer
from .filters import BookFilter


class BooksModelViewSet(ModelViewSet):
    queryset = models.Book.objects.all()
    serializer_class = BookModelSerializer
    filter_class = BookFilter


class BookView(APIView):

    def post(self, request):
        """添加图书，添加时图书类型用id序号表示"""
        ser = BookModelSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
        error = ser.errors
        return Response({'msg': error if error else 'success'})

    def get(self, request):
        """显示所有的书籍类型，并返回对应类型中所有图书的数据"""
        the_book = models.Book.objects.all()
        ser = BookModelSerializer(instance=the_book, many=True)
        return Response(ser.data, status=200)


class BookDetailsView(APIView):
    def get(self,request, id):
        """查找"""
        book1 = models.Book.objects.filter(pk=id).first()
        ser = BookModelSerializer(instance=book1)
        return Response(ser.data, status=200)

    def delete(self, request, id):  # 删除的逻辑
        models.Book.objects.get(pk=id).delete()
        return Response("已删除")

    def put(self, request, id):
        """更新"""
        updae_book = models.Book.objects.get(pk=id)
        serializer = BookModelSerializer(instance=updae_book, data=request.data)
        if serializer.is_valid():

            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)


@csrf_exempt     # post安全检查
def chazhao(request):
    """以书名查找"""
    data = json.loads(request.body)       # request.POST用于形式编码的内容.对于JSON，应该直接访问普通的身体body:
    book = models.Book.objects.filter(name__contains=data['name']).first()
    if book:
        ser = BookModelSerializer(instance=book)
        return JsonResponse(ser.data, status=200)
    else:
        return JsonResponse({'msg': '未找到hhh'})

